package cn.yto.wdgj.wdgjgptdigitaltool.service.impl;

import cn.yto.base.page.BasePage;
import cn.yto.base.page.Sort;
import cn.yto.response.BaseResponse;
import cn.yto.response.DataResult;
import cn.yto.utils.BeanUtil;
import cn.yto.utils.DateUtil;
import cn.yto.utils.JsonUtil;
import cn.yto.utils.StringUtil;
import cn.yto.wdgj.common.constant.CacheCloudConst;
import cn.yto.wdgj.common.constant.RedisKeysConsts;
import cn.yto.wdgj.common.reponse.MutiResponse;
import cn.yto.wdgj.common.utils.CacheCloudUtil;
import cn.yto.wdgj.wdgjgptdigitaltool.entity.dto.request.GptCaseMatcherRequest;
import cn.yto.wdgj.wdgjgptdigitaltool.entity.dto.request.GptTasFallbackRequest;
import cn.yto.wdgj.wdgjgptdigitaltool.entity.dto.response.GptTasFallbackResponse;
import cn.yto.wdgj.wdgjgptdigitaltool.entity.po.Authentication;
import cn.yto.wdgj.wdgjgptdigitaltool.feign.WdgjGptTalkFeignClient;
import cn.yto.wdgj.wdgjgptdigitaltool.feign.request.UserEvent;
import cn.yto.wdgj.wdgjgptdigitaltool.feign.response.BotEvent;
import cn.yto.wdgj.wdgjgptdigitaltool.feign.response.UtterMessage;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.gpt.GptCaseMaintenanceMapper;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.gpt.GptCaseResultMapper;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.gpt.GptTagMaintenanceMapper;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.po.GptCaseResult;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.po.GptTagMaintenance;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.po.GptCaseMaintenance;
import cn.yto.wdgj.wdgjgptdigitaltool.service.GptTaskDialogService;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class GptTaskDialogServiceImpl implements GptTaskDialogService {

    private final static String salt = "822d7db759ec103125b19f12504c73dc8348d06fae3b895524ab74630c0e3ced";

    @Autowired
    private WdgjGptTalkFeignClient wdgjGptTalkFeignClient;

    @Autowired
    private GptCaseResultMapper gptCaseResultMapper;

    @Autowired
    private GptTagMaintenanceMapper gptTagMaintenanceMapper;

    @Autowired
    private GptCaseMaintenanceMapper gptCaseMaintenanceMapper;

//    private static final String TOKEN = "401bae4b-62de-4ec0-ab81-b1fb82de9edc";


    @Override
    public void execute(GptCaseMatcherRequest gptCaseMatcherRequest) {
        if (!gptCaseMatcherRequest.getIsBatch() && gptCaseMatcherRequest.getId() == null) {
            return;
        }
        // 生成会话ID, 同一个请求唯一ID
        String sessionId = UuidUtils.generateUuid().replace("-", "").toLowerCase();
        // 生成批次ID, 同一个请求唯一ID
        String batchId = DateUtil.formatDate(new Date(), "yyyyMMddHHmmss");
        // 查询测试用例表获取回归数据
        LambdaQueryWrapper<GptCaseMaintenance> lambdaQueryWrapper = new LambdaQueryWrapper<GptCaseMaintenance>();
        lambdaQueryWrapper.in(GptCaseMaintenance::isDel, false);
        if (!gptCaseMatcherRequest.getIsBatch()) {
            lambdaQueryWrapper.in(GptCaseMaintenance::getId, gptCaseMatcherRequest.getId());
        }
        List<GptCaseMaintenance> gptCaseMaintenances = gptCaseMaintenanceMapper.selectList(lambdaQueryWrapper);
        // 随机生成一个token,塞到redis里
        Authentication authentication = new Authentication();
        String token = UuidUtils.generateUuid().toLowerCase();
        authentication.setAuthTicket(token);
        CacheCloudUtil.set(CacheCloudConst.WDGJ_COMMON_CLUSTER, String.format(RedisKeysConsts.ACCESS_TOKEN_PC_KEY, token), authentication, 5, TimeUnit.HOURS);
        // Header里增加token和渠道，dialog接口验签需要
        Map<String, String> headerMap = new HashMap();
        headerMap.put("token", token);
        headerMap.put("accessToken", token);
        headerMap.put("channel", "wdgj_pc");
        Date requestDate = new Date();
        for (GptCaseMaintenance gptCaseMaintenance : gptCaseMaintenances) {
            UserEvent userEvent = new UserEvent();
            userEvent.setSender(sessionId);
            userEvent.setMessage(gptCaseMaintenance.getMatcherContent());
            UserEvent.Metadata metadata = userEvent.getMetadata();
            metadata.setToken(token);
            metadata.setWdgjToken(token);
            // 调talk接口
            Date requestDateTime = new Date();
            DataResult<UtterMessage> dialog = null;
            try {
                dialog = wdgjGptTalkFeignClient.dialog(headerMap, userEvent);
            } catch (Exception e) {
                log.error("调用talk主项目 dialog接口出现异常=", e);
                dialog = DataResult.fail("接口请求失败，请重新操作");
            }
            Date responseDateTime = new Date();
            // 构建GptCaseResult对象 用于落库
            GptCaseResult gptCaseResult = new GptCaseResult();
            gptCaseResult.setBatchId(batchId); // 20250218135700
            gptCaseResult.setSessionId(sessionId);
            gptCaseResult.setCaseContent(gptCaseMaintenance.getMatcherContent());
            gptCaseResult.setIntentName(gptCaseMaintenance.getIntentName());
            gptCaseResult.setTag(gptCaseMaintenance.getTag());
            gptCaseResult.setRequestTime(requestDateTime);
            gptCaseResult.setResponseTime(responseDateTime);
            if (dialog.getStatus() == 0) {
                UtterMessage data = dialog.getData();
                if (data != null) {
                    gptCaseResult.setMessageId(data.getMessageId());
                    List<BotEvent> messages = data.getMessages();
                    if (CollectionUtils.isNotEmpty(messages)) {
                        BotEvent botEvent = messages.get(0);
                        BotEvent.Custom custom = botEvent.getCustom();
                        Object dataObj = custom.getData();
                        Object copyTextObj = JSON.parseObject(dataObj.toString(), Map.class).get("copyText");
                        if (copyTextObj == null) {
                            copyTextObj = JSON.parseObject(dataObj.toString(), Map.class).get("text");
                        }
                        if (copyTextObj != null) {
                            gptCaseResult.setResponseText(copyTextObj.toString());
                        } else {
                            gptCaseResult.setResult(false);
                        }
                        // 判断意图是否一致
                        if (gptCaseMaintenance.getTag().equals(custom.getTag())) {
                            if (StringUtil.isNotBlank(gptCaseResult.getResponseText())) {
                                matcherContent(gptCaseResult);
                            } else {
                                gptCaseResult.setResponseText("dialog接口指定字段没有返回值");
                                gptCaseResult.setResult(false);
                            }
                        } else {
                            gptCaseResult.setResponseText("TAG匹配不一致");
                            gptCaseResult.setResult(false);
                        }
                    }
                }
            } else {
                gptCaseResult.setResponseText("接口请求失败，请重新操作");
                gptCaseResult.setResult(false);
            }
            gptCaseResultMapper.insert(gptCaseResult);
        }
        Date requestEndDate = new Date();
        // 做汇总数据统计
        /*
        1、根据batchId查询出所有数据，然后做统计
        2、统计的数据落库
         */
    }

    @Override
    public DataResult<MutiResponse<GptTasFallbackResponse>> getPage(GptTasFallbackRequest request) {
        StringBuilder logBuilder = new StringBuilder("【根据条件获取列表】paramData request=[ " + JsonUtil.toJson(request) + " ]，");
        LambdaQueryWrapper<GptCaseResult> lambdaQueryWrapper = new LambdaQueryWrapper<GptCaseResult>();
        if (request.getId() != null) {
            lambdaQueryWrapper.in(GptCaseResult::getId, request.getId());
        }
        if (StringUtil.isNotBlank(request.getBatchId())) {
            lambdaQueryWrapper.in(GptCaseResult::getBatchId, request.getBatchId());
        }
        if (StringUtil.isNotBlank(request.getIntentName())) {
            lambdaQueryWrapper.in(GptCaseResult::getIntentName, request.getIntentName());
        }
        if (StringUtil.isNotBlank(request.getTag())) {
            lambdaQueryWrapper.in(GptCaseResult::getTag, request.getTag());
        }
        if (request.getResult() != null) {
            lambdaQueryWrapper.in(GptCaseResult::getResult, request.getResult());
        }
        if (StringUtil.isNotBlank(request.getCaseContent())) {
            lambdaQueryWrapper.like(GptCaseResult::getCaseContent, request.getCaseContent());
        }

        lambdaQueryWrapper.orderByDesc(GptCaseResult::getBatchId, GptCaseResult::getResponseTime);

        BasePage page = new BasePage();
        page.setCurrentPage(request.getPageNo());
        page.setPageSize(request.getPageSize());
        page.setQueryCount(true);

        Page<GptCaseResult> pageResult = PageHelper.startPage(page.getCurrentPage(),
                page.getPageSize(), page.getQueryCount()).doSelectPage(() -> gptCaseResultMapper.selectList(lambdaQueryWrapper));

        int resultNum = org.apache.commons.collections.CollectionUtils.isEmpty(pageResult.getResult()) ? 0 : pageResult.getResult().size();
        logBuilder.append("接口查询数据量= [ ").append(resultNum).append(" ]，");

        MutiResponse<GptTasFallbackResponse> pageResponse = new MutiResponse<>();
        List<GptTasFallbackResponse> myWorkOrderResponses = BeanUtil.copyByList(pageResult.getResult(), GptTasFallbackResponse.class);

        pageResponse.setItems(myWorkOrderResponses);
        pageResponse.setPageNo(request.getPageNo());
        if (CollectionUtils.isNotEmpty(pageResult.getResult())) {
            pageResponse.setLimit(pageResult.getResult().size());
        } else {
            pageResponse.setLimit(0);
        }
        if (pageResponse.getLimit() < request.getPageSize()) {
            // 查询出来的接口比分页参数少，则认为没有更多数据了
            pageResponse.setMorePage(false);
        } else {
            pageResponse.setMorePage((long) page.getCurrentPage() * page.getPageSize() < pageResult.getTotal());
        }
        pageResponse.setTotal(pageResult.getTotal());
        log.info(logBuilder.toString());
        return DataResult.ok(pageResponse);
    }

    private void matcherContent(GptCaseResult gptCaseResult) {
        List<GptTagMaintenance> gptTagMaintenances = gptTagMaintenanceMapper.selectByTag(gptCaseResult.getTag());
        for (GptTagMaintenance gptTagMaintenance : gptTagMaintenances) {
            String matcherMode = gptTagMaintenance.getMatcherMode();
            if (GptTagMaintenance.MatcherMode.BLUR.name().equals(matcherMode)) {
                // 模糊匹配
                if (gptCaseResult.getResponseText().contains(gptTagMaintenance.getMatcherContent())) {
                    gptCaseResult.setResult(true);
                    gptCaseResult.setMatcherContent(gptTagMaintenance.getMatcherContent());
                    return;
                }
            }

            if (GptTagMaintenance.MatcherMode.REGULAR.name().equals(matcherMode)) {
                // 正则匹配
                Pattern pattern = Pattern.compile(gptTagMaintenance.getMatcherContent());
                Matcher matcher = pattern.matcher(gptCaseResult.getResponseText());
                if (matcher.find()) {
                    gptCaseResult.setResult(true);
                    gptCaseResult.setMatcherContent(gptTagMaintenance.getMatcherContent());
                    return;
                }
            }
        }
        gptCaseResult.setResult(false);
    }


}
